<?php

namespace app\admin\controller;

use app\common\model\MarketcateModel;
use think\Request;
use cmf\controller\AdminBaseController;
use think\Db;
use think\Validate;
use tree\Tree;

/*车品超市 分类*/

class CategoryController extends AdminBaseController
{
    /**
     * 分类列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $result = db('marketcate')->order(["list_order" => "ASC"])->select()->toArray();
        $tree = new Tree();
        $tree->icon = ['&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─', '&nbsp;&nbsp;&nbsp;└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $newMenus = [];
        foreach ($result as $m) {
            $newMenus[$m['id']] = $m;
        }
        foreach ($result as $key => $value) {
            $result[$key]['parent_id_node'] = ($value['parent_id']) ? ' class="child-of-node-' . $value['parent_id'] . '"' : '';
            $result[$key]['style'] = empty($value['parent_id']) ? '' : 'display:none;';
            //如果是二级分类 不让其添加子类
            if ($value['parent_id'] != 0) {
                $result[$key]['str_manage'] = '<a class="btn btn-xs btn-primary" href="' . url("edit", ["id" => $value['id'], "menu_id" => $this->request->param("menu_id")]) . '">' . lang('EDIT') . '</a>  
                                               <a class="btn btn-xs btn-danger js-ajax-delete" href="' . url("delete", ["id" => $value['id'], "menu_id" => $this->request->param("menu_id")]) . '">' . lang('DELETE') . '</a> ';
            } else {
                $result[$key]['str_manage'] = '<a class="btn btn-xs btn-primary" href="' . url("add", ["parent_id" => $value['id'], "menu_id" => $this->request->param("menu_id")]) . '">' . lang('ADD_SUB_MENU') . '</a> 
                                               <a class="btn btn-xs btn-primary" href="' . url("edit", ["id" => $value['id'], "menu_id" => $this->request->param("menu_id")]) . '">' . lang('EDIT') . '</a>  
                                               <a class="btn btn-xs btn-danger js-ajax-delete" href="' . url("delete", ["id" => $value['id'], "menu_id" => $this->request->param("menu_id")]) . '">' . lang('DELETE') . '</a> ';
            }
            $result[$key]['status'] = $value['status'] ? '<span class="label label-success">' . lang('DISPLAY') . '</span>' : '<span class="label label-warning">' . lang('HIDDEN') . '</span>';

        }
        $tree->init($result);
        $str = "<tr id='node-\$id' \$parent_id_node style='\$style'>
                        <td style='padding-left:20px;'><input name='list_orders[\$id]' type='text' size='3' value='\$list_order' class='input input-order'></td>
                        <td>\$id</td>
                        <td>\$spacer\$name</td>                         
                        <td>\$status</td>
                        <td>\$str_manage</td>
                    </tr>";
        $category = $tree->getTree(0, $str);
        $this->assign("category", $category);
        return $this->fetch();
    }


    /**
     * 后台分类添加
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function add()
    {
        $tree = new Tree();
        $parentId = $this->request->param("parent_id", 0, 'intval');
        $result = Db::name('marketcate')->where('parent_id', 0)->order(["list_order" => "ASC"])->select();
        $array = [];
        foreach ($result as $r) {
            $r['selected'] = $r['id'] == $parentId ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $tree->init($array);
        $selectCategory = $tree->getTree(0, $str);
        $this->assign("select_category", $selectCategory);
        return $this->fetch();
    }


    /**
     * 后台分类添加提交保存
     */
    public function addPost()
    {
        if ($this->request->isPost()) {

            $param = input();
            //验证输入信息
            $rule = [
                'name' => 'require|unique:marketcate',
            ];
            $msg = [
                'name.require' => '标题不能为空',
                'name.unique' => '标题已存在'
            ];
            $validate = Validate::make($rule, $msg);
            $result = $validate->check($param);
            if (!$result) {
                $this->error($validate->getError());
            }

            $res = db('marketcate')->insert($param);
            if ($res) {
                $this->success('操作成功', url('index'));
            } else {
                $this->error('操作失败');
            }
        }
    }

    /**
     * 后台分类编辑
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */

    public function edit()
    {
        $tree = new Tree();
        $id = $this->request->param("id", 0, 'intval');
        $rs = Db::name('marketcate')->where("id", $id)->find();
        $result = Db::name('marketcate')->where('parent_id', 0)->order(["list_order" => "ASC"])->select();
        $array = [];
        foreach ($result as $r) {
            $r['selected'] = $r['id'] == $rs['parent_id'] ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
        $tree->init($array);
        $selectCategory = $tree->getTree(0, $str);
        $this->assign("data", $rs);
        $this->assign("select_category", $selectCategory);
        return $this->fetch();
    }

    /**
     * 后台分类编辑提交保存
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            $param = input();
            $rule = [
                'name' => 'require|unique:marketcate',
            ];
            $msg = [
                'name.require' => '标题不能为空',
                'name.unique' => '标题已存在'
            ];
            $validate = Validate::make($rule, $msg);
            $result = $validate->check($param);
            if (!$result) {
                $this->error($validate->getError());
            }
            $res = db('marketcate')->where('id', $param['id'])->update($param);
            if ($res) {
                $this->success('操作成功', url('index'));
            } else {
                $this->error('操作失败');
            }
        }
    }

    /**
     * 菜单删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete()
    {
        $id = $this->request->param("id", 0, 'intval');
        $count = Db::name('marketcate')->where("parent_id", $id)->count();
        if ($count > 0) {
            $this->error("该菜单下还有子菜单，无法删除！");
        }
        if (Db::name('marketcate')->delete($id) !== false) {
            $this->success("删除菜单成功！");
        } else {
            $this->error("删除失败！");
        }
    }


    /**
     * 排序
     */
    public function listOrder()
    {
        $MarketcateModel = new MarketcateModel();
        parent::listOrders($MarketcateModel);
        $this->success("排序更新成功！");
    }


}
